package com.tledu.study_springboot.controller;

import com.tledu.study_springboot.domain.Student;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/ai")
public class AiController {
    @RequestMapping("/getString")
    @ResponseBody
    public String getString() {
        return "我们想直接返回一个字符串";
    }

    @RequestMapping("/getMap")
    @ResponseBody
    public Map<String, Object> getMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "这是放在json里的值");
        Student stu = new Student();
        stu.setName("张三丰");
        map.put("student", stu);
        return map;
    }

    @RequestMapping("/ajax")
    public String ajax() {
        return "ajax";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/plant")
    public String plant() {
        return "植物识别";
    }

    @RequestMapping("/contact")
    public String contactUs() {
        return "联系我们";
    }

    @RequestMapping("/plantIdentification")
    @ResponseBody
    public Map<String, Object> plantIdentification(String imgUrl) {
        //需要使用restTemplate发送请求
        RestTemplate restTemplate = new RestTemplate();
        // 调用接口之前，确定：
        //      1. 接口地址
        String url = "http://ai.shangyuninfo.com/api/flowers/identification/processImageByUrl/";
        //      2. 接口的请求方式是什么 POST
        //      3. 接口参数是什么 fileUrl
        // 发送post请求的时候，需要构建HttpEntity ，这个请求题主要由请求头和请求体组成
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/x-www-form-urlencoded");
        // 构建请求体
        LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.put("fileUrl", Collections.singletonList(imgUrl));
        // 构建httpEntity
        HttpEntity<LinkedMultiValueMap<String, String>> request = new HttpEntity<>(params, httpHeaders);
        HashMap<String, Object> res = restTemplate.postForObject(url, request, HashMap.class);
        return res;
    }

}
